package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import kr.hkit.androidcomplete03.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {
	Bitmap mBack;
	ArrayList<Ball> arBall;
	final static int DELAY=50;
	public MyView(Context context) {
		super(context);
		mBack=BitmapFactory.decodeResource(context.getResources(), R.drawable.me);
		arBall=new ArrayList<>();
		mHandler.sendEmptyMessageDelayed(0, DELAY);
		
	}
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			Ball newBall=Ball.create((int)event.getX(), (int)event.getY());
			arBall.add(newBall);
			invalidate();
			return true;
		}
		return false;
		
	}
	protected void onDraw(Canvas canvas) {
		Rect dst=new Rect(0,0,getWidth(),getHeight());
		canvas.drawBitmap(mBack, null, dst,null);
		for(int i=0; i<arBall.size(); i++){
			arBall.get(i).Draw(canvas);
		}
	};
	Handler mHandler=new Handler(){

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Ball b;
			for(int i=0; i<arBall.size(); i++){
				b=arBall.get(i);
				b.Move(getWidth(), getHeight());
				if(b.count>4){
					arBall.remove(i);
					i--;
				}
			}
			invalidate();
			mHandler.sendEmptyMessageDelayed(0, DELAY);
		}
		
	};
}
